local nkLibTables = LibStub("nkLibTables");

local VERSION = "09";
local nkLibChannels = LibStub:NewLibrary("nkLibChannels", VERSION);

if not nkLibChannels then
    return	-- already loaded and no upgrade necessary
end

-- Checks if a channel is available

nkLibChannels.IsChannelAvailable = function (CName)

	local ChannelList = {GetChannelList()};	
	if (nkLibTables.IsMember (ChannelList, CName) == true) then
		--DEFAULT_CHAT_FRAME:AddMessage ("true");
		return true;		
	else
		--DEFAULT_CHAT_FRAME:AddMessage ("false");
		return false;
	end;

end;

-- Creates a new channel

nkLibChannels.CreateChannel = function (CName, CPassword)

	if nkLibChannels.IsChannelAvailable(CName) == true then
		--DEFAULT_CHAT_FRAME:AddMessage ("Channel already available");
		return false;
	end;	

	local channel = CreateChannel(CName, CPassword);
	
	if ( channel < 1 or channel > 9 ) then
		return false;
	end;
	
	DEFAULT_CHAT_FRAME.channelList[channel] = CName;
	
	--table.insert (nkLibChannels.ChannelList, {name=CName});
	return true;  	
end;

-- Joins an existing channel

nkLibChannels.JoinChannel = function (CName, CPassword, callBackFunc)

	if nkLibChannels.IsChannelAvailable(CName) == true then	
		-- Channel is available
	
		if callBackFunc ~= nil then
			callBackFunc(true);
		end;
		
		return 1;
	end;

	local channel = JoinChannel(CName, CPassword);
	
	if ( channel < 1 or channel > 9 ) then
		return -1;
	end;

	DEFAULT_CHAT_FRAME.channelList[channel] = CName;
	return 0;	  	
end;

-- Leaves a channel if available

nkLibChannels.LeaveChannel = function (CName)

	if nkLibChannels.IsChannelAvailable(CName) == false then
		--DEFAULT_CHAT_FRAME:AddMessage ("Channel not available");
		return false;
	else
		LeaveChannel(CName);
		return true;
	end;	  	
end;

nkLibChannels.GetChannelNo = function (CName)

	local ChannelList = {GetChannelList()};
	
	for idx = 1, #ChannelList, 2 do
		local ChannelNo = ChannelList [idx];
		local ChannelText = ChannelList [idx+1];
		--DEFAULT_CHAT_FRAME:AddMessage(ChannelText);
		if (ChannelText == CName) then
			return ChannelNo;
		end; 
	end;
	
	return nil;

end;